<template>
  <div ref="boxRef" class="flex items-center overflow-hidden">
    <template v-for="(action, i) in actions" :key="i">
      <ElDivider v-if="i > 0" direction="vertical" />
      <ElButton type="primary" link @click.stop="doAction(action, unit, row)">
        <icon :icon="getIcon(action)" :color="action.color" :size="action.size" :hover-color="action.hoverColor" class="mr1" />
        {{ getLabel(action) }}
      </ElButton>
    </template>
    <template v-if="menuActions.length > 0">
      <ElDivider v-if="actions.length > 0" direction="vertical" />
      <ActionMenu :actions="menuActions" :row="row" />
    </template>
  </div>
</template>
<script lang="ts" setup>
  import { inject, nextTick, onMounted, reactive, ref } from 'vue'
  import { ElDivider, ElButton } from 'element-plus';
  import ActionMenu from './ActionMenu.vue';
  import { Icon } from '@/components/Icon'
  import { Action, Unit } from '@/seed-application/types';
  import { doAction } from '@/seed-application/actions';
  import { getIcon, getLabel } from '@/seed-application/utils/ActionUtil';
  import { useUserStore } from '@/store';
  import { unitKey } from '@/seed-application';

  const props = defineProps<{actions: Record<string, Action>, row: any}>()
  const unit = inject<Unit>(unitKey, void 0)

  const boxRef = ref()
  const actions = reactive<Action[]>([])
  const menuActions = reactive<Action[]>([])
  const userStore = useUserStore()
  for(const actionName in props.actions) {
    const action = props.actions[actionName]
    const permission = action.micro ? `${action.micro.name}.` : '' + action.seed.name + '.' + actionName
    if(userStore.has(permission)) actions.push(action)
  }

  onMounted(async () => {
    while(boxRef.value.offsetWidth < boxRef.value.scrollWidth) {
      if(actions.length == 0) break
      menuActions.unshift(actions.pop())
      await nextTick()
    }

    if(actions.length > 0 && menuActions.length > 0) menuActions.unshift(actions.pop())
  })
</script>